import { hex2int, int2hex } from './types'

// 分解rgb字符串(20,15,253) => [20, 15, 253]
export function rgb2array(rgb) {
  const reg = /(\d{1,3}),(\d{1,3}),(\d{1,3})/
  const arr = reg.exec(rgb)
  return arr === null
    ? null
    : [parseInt(arr[1]) % 256, parseInt(arr[2]) % 256, parseInt(arr[3]) % 256]
}

export function array2rgb(rgb) {
  return '(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')'
}

// 将RGB转换成HEX
export function rgb2hex(rgb, prefix = '') {
  function hex(x) {
    return ('0' + parseInt(x).toString(16)).slice(-2)
  }
  const arr = rgb2array(rgb)
  const _hex = hex(arr[0]) + hex(arr[1]) + hex(arr[2])
  return prefix + _hex.toUpperCase()
}

export function rgbArray2hex(rgb, prefix = '') {
  function hex(x) {
    return ('0' + parseInt(x).toString(16)).slice(-2)
  }
  const _hex = hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2])
  return prefix + _hex.toUpperCase()
}

export function rgbObject2Hex(rgb, prefix = '') {
  return rgbArray2hex([rgb.r, rgb.g, rgb.b], prefix)
}

// 16进制转换为rgb
// 7B374E => (123,55,78)
export function hex2Rgb(hexValue, prefix = '') {
  const s = hexValue.slice(prefix.length, hexValue.length)
  return (
    '(' +
    parseInt('0x' + s.slice(0, 2)) +
    ',' +
    parseInt('0x' + s.slice(2, 4)) +
    ',' +
    parseInt('0x' + s.slice(4, 6)) +
    ')'
  )
}

// rgb转换为整数
export function rgbArray2int(rgb) {
  return hex2int(rgbArray2hex(rgb))
}

// 整数转换为rgb
export function int2rgbArray(intValue) {
  return rgb2array(hex2Rgb(int2hex(intValue)))
}

export function hex2rgbArray(hex, prefix = '') {
  return rgb2array(hex2Rgb(hex, prefix))
}

export function hex2rgbObject(hex, prefix = '') {
  const ar = rgb2array(hex2Rgb(hex, prefix))
  return {
    r: ar[0],
    g: ar[1],
    b: ar[2]
  }
}

export function rgb2int(rgb) {
  return hex2int(rgb2hex(rgb))
}

export function int2rgb(intValue) {
  return hex2Rgb(int2hex(intValue))
}

export function fromRgb(r, g, b) {
  return rgbArray2int([r, g, b])
}

export function fromRgb2(r, g, b, prefix = '') {
  return rgbArray2hex([r, g, b], prefix)
}

export function reverseHexColor(hexValue, prefix = '') {
  const s = hexValue.slice(prefix.length, hexValue.length)
  return s.slice(4, 6) + s.slice(2, 4) + s.slice(0, 2)
}

export function reverseRgbColor(rgb) {
  const arr = rgb2array(rgb)
  const tmp = arr[0]
  arr[0] = arr[2]
  arr[2] = tmp
  return array2rgb(arr)
}
